#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<signal.h>
#include<wait.h>
#include<sys/time.h>
#include<fcntl.h>
#include<unistd.h> 
#include<pthread.h>

void myfunc(int signum){
	int wstatus;
	while(waitpid(0, &wstatus, WNOHANG) != -1){
		if(WIFEXITED(wstatus)){
			printf("child exit by %d\n", WEXITSTATUS(wstatus));
		}
	}
	return;
}



int main(int argc, char *args[])
{
	int pid, i;
	sigset_t set;
	
	//防止子进程先比父进程结束,导致SIHCHLD信号收到后忽略,设置CHILD先屏蔽;
	sigaddset(&set, SIGCHLD);
	sigprocmask(SIG_BLOCK, &set, nullptr);


	for(i = 0; i < 15; i++){
		pid = fork();
		if(pid == 0)
			break;
	}

	if(i == 15){
		struct sigaction act, oldact;

		act.sa_flags = 0;
		sigemptyset(&act.sa_mask);
		act.sa_handler = myfunc;

		int ret = sigaction(sigchld, &act, &oldact);
		if(ret < 0){
			perror("sigaction error");
			exit(1);
		}
		
		//解除屏蔽
		sigprocmask(SIG_UNBLOCK, &set, nullptr);
		while(1);
	}

	else{
		printf("this is child, pid is %d, ppid is %d\n", getpid(), getppid());
		exit(i);
	}
	
	return 0;
}
